#include "../FilterSDK/ia.h"
#include "SerialPort.h"
#include <conio.h>
#include <string>

void OnDataReceived(const unsigned char* pBuffer, int bufferSize)
{
	IA_TRACE("%d bytes of data received on callback, convert to string as: %s", bufferSize, pBuffer);
}

int main()
{
	int status = IA_L_ERR;
	CSerialPort _port;

	status = _port.Open(1, 115200, EParity::MarkParity, 8, EStopBits::OneStopBit, EFlowControl::NoFlowControl);
	STATUS_CHECK

	status = _port.Open(1, 115200, EParity::MarkParity, 8, EStopBits::OneStopBit, EFlowControl::NoFlowControl);
	STATUS_CHECK

	std::string text = "Hello world";
	status = _port.WriteString(text);
	STATUS_CHECK

	status = _port.Flush();
	STATUS_CHECK

	int len;
	status = _port.BytesWaiting(&len);
	STATUS_CHECK

	IA_TRACE("Press any button to  go to callback mode");
	_getch();
	//status = _port.SetSerialDataCallback(&OnDataReceived);
	//STATUS_CHECK

	int bufferSize = 1024;
	unsigned char* buffer = (unsigned char*)malloc(bufferSize);

	// test thread safe
	// Now please send data on serial debug program to test RW confliction
	for (int i = 0; i < 100; i++) {
		sprintf_s((char*)buffer, 1024, "Hello %d", i);
		_port.WriteString(text);
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
	}

	IA_TRACE("Press any button to  remove callback");
	_getch();
	status = _port.SetSerialDataReceiver(NULL);
	STATUS_CHECK

	return 0;

	status = _port.ReadBytes(buffer, bufferSize, len);
	STATUS_CHECK

	// Free here to test receiving thread
	getchar();

	_port.Close();

	free(buffer);


	IA_RETURN_OK
}